package cn.sangyy.gift.utils;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author SangYY
 * @date: 2023/06/24/14:21
 */
public class CosUtils {

    private static final String bucketName = "sangyy-gift-1312587115";
    private static final String region = "ap-chengdu";
    private static final String appId = "1312587115";
    private static final String secretId = "AKIDnS01oSMEzb5PhroAXhnlYCf2INI1ZwAA";
    private static final String secretKey = "ynV3TWN5Yr26ygBUdXHtTN4hCUIvDPUP";
    private static final String domainName = "https://sangyy-gift-1312587115.cos.ap-chengdu.myqcloud.com";

    public static String uploadImage(MultipartFile file) throws Exception {
        BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        //这是bucket区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        //生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        //设置线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(16);
        TransferManager transferManager = new TransferManager(cosClient, threadPool);
        UUID uuid = UUID.randomUUID();
        String filename = file.getOriginalFilename();
        assert filename != null;
        String prefix = filename.substring(filename.lastIndexOf("."));
        File newFile = File.createTempFile(filename, prefix);
        file.transferTo(newFile);
        String key = "images/rlg/"+uuid+"_"+filename;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, newFile);
        Upload upload = transferManager.upload(putObjectRequest);
        upload.waitForCompletion();
        Date date = new Date(new Date().getTime() + 5 * 60 * 10000);
        URL url = cosClient.generatePresignedUrl(bucketName, key, date);
        String path = domainName+url.getPath();
        return path;
    }

    public static void deleteImage(String path) {
        BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        //这是bucket区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        //生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        String key = path.substring(domainName.length() + 1);
        cosClient.deleteObject(bucketName,key);
    }

}
